package com.suray.attendance.contacts.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiUserListidRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserListRequest;
import com.dingtalk.api.response.OapiUserListidResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserListResponse;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suray.attendance.common.dingding.service.DingAccessTokenService;
import com.suray.attendance.common.utils.LoggerUtil;
import com.suray.attendance.model.pojo.UserInfo;
import com.suray.attendance.contacts.service.DingDeptService;
import com.suray.attendance.contacts.service.DingUserService;
import com.taobao.api.ApiException;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author: jianglinyu
 * @CreateTime: 2023-07-08  14:06
 * @Description: TODO
 * @Version: 1.0
 */
@CommonsLog
@Service
public class DingUserServiceImpl implements DingUserService {

    @Resource
    private DingAccessTokenService dingAccessTokenService;
    @Resource
    private DingDeptService dingDeptService;

    /**
     * @description: 根据部门id获取员工userId列表  创建一个userInfo实例我们可以填充它的部门和userId
     * @author: jianglinyu
     * @date: 2023/7/11 9:04
     * @return*/
    @Override
    public List<String> getUserListByDeptId(Long deptId) {
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/listid");
        OapiUserListidRequest req = new OapiUserListidRequest();
        req.setDeptId(1L);
        OapiUserListidResponse rsp = null;
        try {
            rsp = client.execute(req, dingAccessTokenService.getAccessToken());
            if(rsp.getErrcode()==0){
                String body = rsp.getBody();
                ObjectMapper objectMapper = new ObjectMapper();
                // 将JSON字符串解析为JsonNode对象
                JsonNode rootNode = objectMapper.readTree(body);
                // 获取userid_list数组
                JsonNode useridListJsonNode = rootNode.get("result").get("userid_list");
                // 遍历数组并提取元素
                List<String> extractedValues = new ArrayList<>();
                if (useridListJsonNode.isArray()) {
                    Iterator<JsonNode> iterator = useridListJsonNode.elements();
                    while (iterator.hasNext()) {
                        String value = iterator.next().asText();
                        extractedValues.add(value);
                    }
                }
                return extractedValues;
            }
        } catch (Exception e) {
            LoggerUtil.error(e.getMessage(), DingUserServiceImpl.class);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param deptId
     * @description: 获取部门员工详情
     * @author: jianglinyu
     * @date: 2023/7/11 10:39
     * @return List<UserInfo>
     */
    @Override
    public List<UserInfo> getUserInfoFromDingDingByDeptId(String accessToken,Long deptId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
            OapiV2UserListRequest req = new OapiV2UserListRequest();
            req.setDeptId(deptId);
            req.setCursor(0L);
            req.setSize(100L);
            req.setOrderField("modify_desc");
            req.setContainAccessLimit(false);
            req.setLanguage("zh_CN");
            OapiV2UserListResponse rsp = client.execute(req,accessToken);
            if (rsp.getErrcode()==0){
                String s = JSON.toJSONString(rsp.getResult());
                Map map = JSON.parseObject(s, Map.class);
                Object list = map.get("list");
                List<Map> mattendance = JSONObject.parseArray(list.toString(), Map.class);
                if(mattendance!=null&&mattendance.size()>0){
                    List<UserInfo> userInfoList;
                    return userInfoList = mattendance.stream().map(userMap -> {
                        UserInfo userInfo = new UserInfo();
                        userInfo.setDeptId(deptId);
                        userInfo.setId(userMap.get("userid").toString());
                        userInfo.setUnionId(userMap.get("unionid").toString());
                        userInfo.setName(userMap.get("name").toString());
                        userInfo.setCreateTime(LocalDateTime.now());
                        return userInfo;
                    }).collect(Collectors.toList());
                }

            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.error("获取部门="+deptId+"员工详情异常"+e.getMessage(),DingUserServiceImpl.class);
            throw new RuntimeException("获取部门="+deptId+"员工详情异常");
        }
    }
    /**
     * @param userId
     * @description:根据用户id 获取用户钉钉详细信息
     * @author: jianglinyu
     * @date: 2023/7/11 11:18
     * @return
     */
    @Override
    public String getUserInfoById(String userId) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
            OapiV2UserGetRequest req = new OapiV2UserGetRequest();
            req.setUserid(userId);
            req.setLanguage("zh_CN");
            OapiV2UserGetResponse rsp = client.execute(req, dingAccessTokenService.getAccessToken());
            if(rsp.getErrcode()==0){
                return JSON.toJSONString(rsp.getResult());
            }
        } catch (ApiException e) {
            LoggerUtil.error(e.getMessage(), DingUserServiceImpl.class);
            e.printStackTrace();
        }
        return null;
    }

}